Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

265
Views
Order results by "Best Match" SQL

I'm working on a project which requires the user to search for certain categories of products. The products have tags such as: T-shirt, Jumper, hat and I am currently displaying the results ordered by the amount of likes. Here's my SQL statement:

SELECT * 
FROM products 
WHERE keywords LIKE '%$query%' 
ORDER BY likes DESC LIMIT 50;

But the issue is that if let's say someone searched "hat" but a more popular word was "chatterbox" in the database, it would come up with that first because it has more likes.

So to put it in pseudo code:

SELECT * 
FROM products 
WHERE keywords LIKE '%$query%' 
ORDER BY "BEST MATCH" LIMIT 50;

and the result would ideally be:

2 results:
Hat: 26 likes,
Chatterbox: 234 likes,

Instead of:

2 results:
Chatterbox : 234 likes,
Hat: 26 likes,

So is there a way to do this?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

In the ORDER BY clause check first if there is an exact match or (if you want it) keywords starts with '$query':

SELECT * 
FROM products 
WHERE keywords LIKE '%$query%' 
ORDER BY keywords = '$query' DESC, -- 1st keywords with exact match
         keywords LIKE '$query%' DESC, -- 2nd keywords which start with '$query'    
         likes DESC -- 3d likes
LIMIT 50;
over 4 years ago · Santiago Trujillo Report

0

You can try this:

(SELECT * FROM products WHERE keywords LIKE '$query')
union
(SELECT * FROM products WHERE keywords LIKE '%$query%' order by likes desc LIMIT 50);

With first query you get the exact match and with second, others matches order by likes.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!